package com.example.demo.concurrent.unsafe;

import com.example.demo.concurrent.AtomicTest.MyUnSafe.UnSafeAccessor;
import sun.misc.Unsafe;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-09-15
 * Time: 13:08
 */
public class AtomicInt {
    // 要操作的数据
    private int data;
    // UNSAFE对象
    private static final Unsafe unsafe;
    // 得到操作数据的偏移量
    private static final long DATA_OFFSET;
    static {
        // 初始化unsafe对象
        unsafe = UnSafeAccessor.getUnsafe();
        try {
            // 初始化偏移量
            DATA_OFFSET = unsafe.objectFieldOffset(AtomicInt.class.getDeclaredField("data"));
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    public int getAndIncrement(int next) {
        //得到旧值
        int oldValue;
        while(true) {
            oldValue = this.data;
            // 尝试修改为新值
            if(unsafe.compareAndSwapInt(this,DATA_OFFSET,oldValue,data)) {
                return data;
            }
        }
    }

    public int getData() {
        return data;
    }
}
